package com.tuanzi.loan.business.service.receipt.product.impl;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.receipt.product.ReceiptProductCondition;
import com.tuanzi.loan.business.entity.receipt.product.ReceiptProductInfo;
import com.tuanzi.loan.business.repository.receipt.product.ReceiptProductConditionRepository;
import com.tuanzi.loan.business.service.receipt.product.ReceiptProductConditionService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.server.loan_base.constant.LoanReceiptProductStatus;

@Debug
@Service
@Transactional
public class ReceiptProductConditionServiceImpl extends BaseAuditServiceImpl<ReceiptProductCondition, Long> implements ReceiptProductConditionService {
	@Autowired
	private ReceiptProductConditionRepository receiptProductConditionRepository;

	@Override
	public ReceiptProductCondition findReceiptProductConditionByProductId(Long productId) {
		return receiptProductConditionRepository.findReceiptProductConditionByProductIdAndStatusIn(productId,
				Lists.newArrayList(LoanReceiptProductStatus.ONLINE, LoanReceiptProductStatus.OFFLINE));
	}

	@Override
	public ReceiptProductCondition findReceiptProductConditionByProductInfo(ReceiptProductInfo receiptProductInfo) {
		if (Objects.nonNull(receiptProductInfo) && null != receiptProductInfo.getId()) {
			LoanReceiptProductStatus status = receiptProductInfo.getStatus();
			List<ReceiptProductCondition> list = null;
			if (LoanReceiptProductStatus.ONLINE == status || LoanReceiptProductStatus.OFFLINE == status) { // 上线产品条件
				list = receiptProductConditionRepository.findReceiptProductConditionsByProductIdAndStatusIn(receiptProductInfo.getId(),
						Lists.newArrayList(LoanReceiptProductStatus.ONLINE, LoanReceiptProductStatus.OFFLINE));
			} else {
				list = receiptProductConditionRepository.findReceiptProductConditionsByProductIdAndStatusIn(receiptProductInfo.getId(),
						Lists.newArrayList(LoanReceiptProductStatus.AUDIT, LoanReceiptProductStatus.AUDIT_AGREE, LoanReceiptProductStatus.AUDIT_REJECT));
			}

			if (list != null && list.size() > 0) {
				return list.get(0);
			}

		}
		return null;
	}

	@Override
	protected JPAAuditRepository<ReceiptProductCondition, Long> getRepository() {
		return receiptProductConditionRepository;
	}
}
